<template>
	<div>
		<input type="text" v-model="prefix" placeholder="start prefix">
		<br>
		<select name="" v-model="selected" size="5">
			<option v-for="item in filterNames" :key="item" :value="item">{{item}}</option>
		</select>
		<br>
		姓：<input type="text" v-model="firstName">
		<br>
		名：<input type="text" v-model="lastName">
		<br>
		<button type="button" @click="create">创建</button>
		<button type="button" @click="update">更新</button>
		<button type="button" @click="del">删除</button>
	</div>
</template>

<script setup>
	import {ref, reactive, watch, computed} from 'vue'
	
	const names = reactive([
		'zhang,san', 'li,si'
	])
	const prefix = ref('')
	const selected = ref('')
	const firstName = ref('')
	const lastName = ref('')
	
	const filterNames = computed(()=>{
		// return prefix.value ? names.filter(item => item.toLocaleLowerCase().startsWith(prefix.value.toLocaleLowerCase())) : [...names],
		return names.filter(item => item.toLocaleLowerCase().startsWith(prefix.value.toLocaleLowerCase()))
	})
	
	watch(selected, (newVal) => {
		[firstName.value, lastName.value] = newVal.split(',')
	})
	
	const create = () => {
		if(handleValid()){
			let fullName = firstName.value + ',' + lastName.value
			if(names.indexOf(fullName) === -1){
				names.push(fullName)
				firstName.value = lastName.value = ''
			}
		}
	}
	
	const update = () => {
		if(handleValid()){
			let fullName = firstName.value + ',' + lastName.value
			let i = names.indexOf(fullName)
			names.splice(i, 1, fullName)
			firstName.value = lastName.value = ''
		}
	}
	
	const del = () => {
		let i = names.indexOf(selected)
		names.splice(i, 1)
		selected.value = firstName.value = lastName.value = ''
	}
	
	const handleValid = () => {
		return firstName.value.trim() && lastName.value.trim()
	}
	
</script>

<style>
</style>